<?php
/**
 * User: b179a9
 * Date: 10/4/11
 * Time: 6:48 PM
 */

namespace Managers;

class ItemsRubrics extends BaseManager
{
    const TIME_IN_CACHE = 1;

    protected $__table = '\Catalog\ItemsRubrics';

    public function getList($parent = null, $tree = false)
    {
        $cacheName = sprintf('items_rubric_%s_%s', $parent, $tree);

        $res = $this->_getCacheManager()->load($cacheName);

        if (!$res) {

            $qb = $this->_em->createQueryBuilder()
                    ->select('r')
                    ->from($this->__table, 'r');
            if (isset($parent)) {
                $qb->andWhere('r.parent = :parent')
                        ->setParameter('parent', $parent);
            } else {
                $qb->andWhere('r.parent is null');
            }

            $res = $qb->getQuery()->getArrayResult();

            if ($tree) {
                foreach ($res as $key => $value) {
                    //Так как максимум 2 уровня, второй проход без построяния дочерних елементов.
                    $res[$key]['children'] = $this->getList($value['id'], false);
                }
            }

            $this->_getCacheManager()->save($res, $cacheName, array('items'), self::TIME_IN_CACHE);
        }
        return $res;
    }

    public function getById($id)
    {
        $res = $this->_em->createQueryBuilder()
                ->select('r,p')
                ->from($this->__table, 'r')
                ->leftJoin('r.parent', 'p')
                ->andWhere('r.id = :id')
                ->setParameter('id', $id)
                ->getQuery()
                ->getArrayResult();
        return count($res) ? $res[0] : false;
    }

    public function save(array $params)
    {
        $object = empty($params['id']) ? new \Catalog\ItemsRubrics()
                : $this->_em->find($this->__table, $params['id']);

        $object->setName($params['name']);
        $parent = empty($params['parent']) ? null : $this->_em->getReference($this->__table, $params['parent']);
        $object->setParent($parent);

        $this->_em->persist($object);
        $this->_em->flush();
    }

    /**
     * Изменяет родительскую рубрику для Drag&Drop.
     * @param $id
     * @param $parent
     * @return void
     */
    function changeParent($id, $parent_id)
    {
        $page = $this->_em->find($this->__table, $id);

        if ($id == $parent_id) {
            return 0;
        }

        if ($page) {
            $parent = $parent_id != 0 ? $this->_em->find($this->__table, $parent_id) : null;
            $page->setParent($parent);

            $this->_em->persist($page);
            $this->_em->flush();
            return 1;
        }
        return 0;
    }
}
